﻿using System.Collections;
using LunchList.ViewModels;
using LunchListCore.Interfaces.Agents;
using LunchListCore.Interfaces.Models;
using Microsoft.Practices.Unity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json.Converters;
using LunchList.Infrastructure;

namespace LunchList.Controllers
{
    public class HomeController : LunchListControlerBase
    {
        [Dependency]
        public ILunchAgent LunchAgent { get; set; }

        public ActionResult Index(string id)
        {
            HomeViewModel vm = new HomeViewModel();

	        if (string.IsNullOrEmpty(id))
	        {
				vm.SelectedDate = DateTime.Now;
	        }
	        else
	        {

				vm.SelectedDate = Convert.ToDateTime(id);
	        }

	        IList<DateTime> upcomingEventDates = this.LunchAgent.GetUpcomingEventDates();
	        if (upcomingEventDates == null)
	        {
		        upcomingEventDates = new List<DateTime>()
		        {
			        DateTime.Now
		        };
	        }

	        List<SelectListItem> upcomingEventDateItems = upcomingEventDates.Select(x => new SelectListItem()
	        {
				Selected = (vm.SelectedDate.DayOfYear == x.DayOfYear && vm.SelectedDate.Year == x.Year),
		        Text = x.ToShortDateString(),
				Value = x.ToString("MM-dd-yyyy")
	        }).ToList();

			vm.AvailableDates = new SelectList(upcomingEventDateItems, "Value", "Text", vm.SelectedDate);
            
            return View(vm);
        }

        public ActionResult GetGuestLists(HomeViewModel guestModel)
        {
            GuestListsViewModel resultVm = new GuestListsViewModel()
            {
                EventDate = guestModel.SelectedDate
            };

            try
            {
                resultVm.GuestLists = new List<GuestListViewModel>();
                if (resultVm.EventDate == default(DateTime))
                {
                    resultVm.EventDate = DateTime.Now;
                }

                Dictionary<IEvent, IList<IGuest>> eventGuests = LunchAgent.GetGuestsAndEvents(resultVm.EventDate);

                if (eventGuests == default(Dictionary<IEvent, IList<IGuest>>))
                {
                    return PartialView("_NoGuestLists", new NoGuestListsViewModel()
                    {
                        EventDate = resultVm.EventDate
                    });
                }
                else
                {
                    foreach (KeyValuePair<IEvent, IList<IGuest>> item in eventGuests)
                    {
                        resultVm.GuestLists.Add(new GuestListViewModel()
                        {
                            GuestListGuests = item.Value.Select(x => new GuestListItemViewModel()
                            {
                                EventId = item.Key.EventId,
                                GuestId = x.GuestId,
                                GuestName = x.Name
                            }).ToList(),
                            CurrentUserGuestId = GuestContext.User.GuestId,
                            EventDate = item.Key.EventDate,
                            EventId = item.Key.EventId,
                            EventName = item.Key.EventName
                            //ModifyAction = action
                        });
                    }
                    return PartialView("_GuestLists", resultVm);
                }
            }
            catch(Exception ex)
            {
                ErrorController errorController = new ErrorController();
                List<string> errors = new List<string>();
				errors.Add(ex.Message);

                ErrorViewModel errorModel = new ErrorViewModel
                {
                    Errors = errors,
                    Action = "GetGuestLists",
                    Controller = "Home",
                    ViewModel = guestModel
                };
                return errorController.DisplayErrorView(errorModel);
            }
        }

        //
        // Post: /Home/AddGuest/
        [HttpPost]
        public ActionResult ModifyGuestList(GuestListViewModel model)
        {
            if (model.IsInError)
            {
                //Return back user input
                return PartialView("_GuestList", model);
            }
            DateTime date = DateTime.Now;
            ModelState.Clear();
            try
            {
                string action = string.Empty;
                if (model.ModifyAction.CompareTo("RSVP") == 0)
                {
                    LunchAgent.AddReservation(GuestContext.User, model);
                    action = "Delete RSVP";
                }
                else if (model.ModifyAction.CompareTo("Delete RSVP") == 0)
                {
                    LunchAgent.RemoveReservation(GuestContext.User, model);
                    action = "RSVP";
                }

                GuestListViewModel guestModel = new GuestListViewModel()
                {
                    GuestListGuests = LunchAgent.GetGuests(model).Select(x => new GuestListItemViewModel()
                    {
                        EventId = model.EventId,
                        GuestId = x.GuestId,
                        GuestName = x.Name
                    }).ToList(),
                    CurrentUserGuestId = GuestContext.User.GuestId,
                    EventDate = model.EventDate,
                    EventId = model.EventId,
                    EventName = model.EventName
                };
            
                return PartialView("_GuestList", guestModel);
            }
            catch (Exception ex)
            {
                ErrorController errorController = new ErrorController();
                List<string> errors = new List<string>();
                errors.Add(ex.Message);
                model.IsInError = true;

                GuestListViewModel guestModel = new GuestListViewModel()
                {
                    GuestListGuests = LunchAgent.GetGuests(model).Select(x => new GuestListItemViewModel()
                    {
                        EventId = model.EventId,
                        GuestId = x.GuestId,
                        GuestName = x.Name
                    }).ToList(),
                    CurrentUserGuestId = GuestContext.User.GuestId,
                    EventDate = model.EventDate,
                    EventId = model.EventId,
                    EventName = model.EventName,
                    IsInError = true
                };

                ErrorViewModel errorModel = new ErrorViewModel
                {
                    Errors = errors,
                    Action = "ModifyGuestList",
                    Controller = "Home",
                    ViewModel = guestModel
                };
                return errorController.DisplayErrorView(errorModel);
            }          
        }
	}
}